<template>
    <div class="doc_create_container" :style="{'height': containerHeight + 'px'}">
        <el-container>
            <el-aside width="360px" class="doc_create_letf">
                <el-scrollbar :height=containerHeight>
                    <el-tree
                        :data="chapterList"
                        node-key="mainId"
                        default-expand-all
                        :expand-on-click-node="false"
                        @node-click="treeNodeClick"
                        >
                        <template #default="{ node, data }">
                            <div class="custom_node_item">
                                <template v-if="data.mainId > 0">
                                    <div class="node_item_title">
                                        <span v-show="data.type == 0">
                                            <i class="far fa-folder"></i>
                                        </span>
                                        <span v-show="data.type == 1">
                                            <i class="far fa-file-lines"></i>
                                        </span>
                                        <span style="margin-left: 3px">{{data.title}}</span>
                                    </div>
                                </template>
                                <template v-if="data.mainId == 0">
                                    <div class="node_item_title node_item_root" >
                                        <span style="font-size: 24px;">{{data.title}}</span>
                                    </div>
                                </template>
                                <div class="node_item_group">
                                    <div class="node_item_operate">
                                        <el-link type="primary" @click.prevent.stop="shareTreeNode(data)" v-if="data.mainId > 0 && data.type == 1">分享</el-link>
                                    </div>
                                    <div class="node_item_operate">
                                        <el-link type="primary" @click.prevent.stop="updateTreeNode(data)" v-if="data.mainId > 0" :disabled="!btOption.btChapterUpdate">编辑</el-link>
                                    </div>
                                    <div class="node_item_operate">
                                        <el-link type="primary" @click.prevent.stop="addTreeNode(data)" :disabled="!(btOption.btChapterSave && data.type == 0)">新增</el-link>
                                    </div>
                                    <div class="node_item_operate">
                                        <el-link type="danger" @click.prevent.stop="deleteTreeNode(data)" :disabled="!(data.mainId > 0 && !data.children && btOption.btChapterDelete)">删除</el-link>
                                    </div>
                                </div>
                            </div>
                        </template>
                    </el-tree>
                </el-scrollbar>
            </el-aside>
            <el-main>
                <div class="bt_save_span" v-show="selectTreeNode.type == 1">
                    <span style="font-size: 20px;">{{selectTreeNode.title}}</span>
                    <el-button-group>
                        <el-button type="primary" icon="RefreshLeft" @click="clearContent">清空内容</el-button>
                        <el-button type="primary" icon="DocumentAdd" @click="saveContent">保存文档</el-button>
                    </el-button-group>
                </div>
                <div id="editor—wrapper" class="doc_span" v-show="selectTreeNode.type == 1">
                    <div id="toolbar-container" style="border-bottom: 1px solid #ccc"></div>
                    <div id="editor-container" :style="{'height': (containerHeight - 110) + 'px'}"></div>
                </div>
            </el-main>
        </el-container>
        <el-dialog
            v-model="chapterOption.isShow"
            :title="chapterOption.title"
            :close-on-click-modal="false" 
            :close-on-press-escape="false"
            @close="chapterDialogClose"
            :before-close="chapterDialogBeforeClose"
            draggable
            width="360px">
            <el-form ref="chapterFormRef" :model="chapterForm" :rules="chapterRules" label-width="80px" size="default">
                <el-form-item label="章节标题" prop="title">
                    <el-input v-model="chapterForm.title" placeholder="请输入章节标题" :clearable="true" />
                </el-form-item>
                <el-form-item label="章节类型" prop="type">
                    <el-select
                        v-model="chapterForm.type"
                        placeholder="请选择章节类型"
                        style="width: 240px"
                        :disabled="chapterOption.type == 1">
                        <el-option
                        v-for="item in chapterTypeList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="排序大小" prop="sort">
                    <el-input-number v-model="chapterForm.sort" style="width: 240px"/>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button size="default" @click="dialogCancel">取 消</el-button>
                <el-button size="default" type="primary" @click="dialogConfirm">确认</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script>
import '@wangeditor/editor/dist/css/style.css'
import { tool } from "@/js/tool.js";
import { ElMessage } from 'element-plus';
import { createEditor, createToolbar } from '@wangeditor/editor/dist/index.js';
import { config } from "@/js/config.js";

let INIT_STATUS = 0;

const editorConfig = { 
    placeholder: '请输入内容...', 
    readOnly: false, 
    autoFocus: true,
    scroll: true
}
const toolbarConfig = {
    excludeKeys: ["uploadImage","uploadVideo","todo"]
}

let docCreateApp = null;

export default {
    name: 'doc-create',
    props: {
        docData: {
            type: Object,
            default: null
        },
        authority: {
            type: Object,
            default: null
        }
    },
    data: function(){
        return {
            btOption: this.authority,
            getDocData: this.docData,
            containerHeight: 500,
            chapterList: null,
            shareCode: null,
            chapterOption: {
                type: 0,//0新增；1更新
                title: '',
                selectData: null,
                isShow: false
            },
            chapterForm: {
                mainId: null,
                infoId: this.docData.mainId,
                title: null,
                parentId: null,
                type: null,
                sort: 1
            },
            chapterRules: {
                title: [
                    { required: true, message: '请填写标题', trigger: 'blur' }
                ],
                type: [
                    { required: true, message: '请选择章节类型', trigger: 'blur' }
                ],
                sort: [
                    { required: true, message: '请填写排序值', trigger: 'blur' }
                ]
            },
            chapterTypeList: [
                {value: 0, label: '目录'},
                {value: 1, label: '内容'},
            ],
            selectTreeNode: {
                type: 1
            },
            editor: {
                editor: null,
                toolbarConfig: {},
                editorConfig: editorConfig,
                mode: 'default',
                html: ''
            },
            curContent: null
        }
    },
    methods: {
        deleteTreeNode: function(row){
            let confirmMessage = "是否删除:"+ row.title +"？";
            const obj = this;
            this.$confirm(confirmMessage).then(function () {
                const param = {
                    mainId: row.mainId
                }
                deleteChapter(obj, param);
            }).catch(function () {});
        },
        updateTreeNode: function(row){
            this.chapterOption.type = 1;
            this.chapterOption.isShow = true;
            this.chapterOption.title = "章节编辑";

            this.chapterForm.mainId = row.mainId;
            this.chapterForm.title = row.title;
            this.chapterForm.parentId = row.parentId;
            this.chapterForm.type = row.type;
            this.chapterForm.sort = row.sort;
        },
        addTreeNode: function(row){
            this.chapterOption.type = 0;
            this.chapterOption.isShow = true;
            this.chapterOption.title = "章节新增";

            this.chapterForm.parentId = row.mainId;
        },
        shareTreeNode: function(row){
            //获取层级索引
            let shareUrl = config.domain + "/" + config.projectRootName+ "/doc/share?shareCode=" + this.shareCode;
            shareUrl += "&treeIndex=" + row.treeIndex;
            navigator.clipboard.writeText(shareUrl)
            .then(() => {
                ElMessage({
                    showClose: true,
                    message: '复制成功',
                    type: 'success'
                });
            })
            .catch(() => {
                ElMessage({
                    showClose: true,
                    message: '复制失败',
                    type: 'error'
                });
            });
        },
        chapterDialogBeforeClose: function(){
            dialogCloseTips(this);
        },
        chapterDialogClose: function(){
            this.chapterForm.mainId = null;
            this.chapterForm.title = null;
            this.chapterForm.parentId = null;
            this.chapterForm.type = null;
            this.chapterForm.sort = 1;

            this.$refs["chapterFormRef"].clearValidate();
        },
        dialogCancel: function(){
            dialogCloseTips(this);
        },
        dialogConfirm: function(){
            const obj = this;
                this.$refs["chapterFormRef"].validate(function(valid) {
                if(valid){
                    if(obj.chapterOption.type == 0){
                        //新增
                        saveChapter(obj);
                    }else{
                        //更新
                        updateChapter(obj);
                    }
                }else{
                    return false;
                }
            });
        },
        treeNodeClick: function(data, node, treeNode, event){
            this.selectTreeNode = data;
            if(data.type == 0){
                this.editor.editor.destroy();
                return;
            }
            this.editor.editor.destroy();
            getContent(this);
        },
        saveContent: function(){
            let content = this.editor.editor.getHtml();
            let contentText = this.editor.editor.getText();
            saveContent(this, content, contentText);
        },
        clearContent: function(){
            let obj = this;
            this.$confirm('是否要清空文档内容').then(function () {
                obj.editor.editor.clear();
            }).catch(function () { });
        },  
        removeEditor: function(){
            if(this.editor.editor != null){
                this.editor.editor.destroy();
            }
        },
        removeKeydown: function(){
            document.onkeydown = null;
        }
    },
    created: function(){
        
    },
    mounted: function(){
        docCreateApp = this;
        const height = document.body.clientHeight;
        this.containerHeight = height - 90;
        createEditorInit(this);
        getChapterList(this);
        createKeydown();
    },
    components: {

    }
}

/**
 * ctrl+s进行保存
 */
function createKeydown(){
    document.onkeydown = function (event) {
        if (event.key === 's' && event.ctrlKey) {
            event.preventDefault();
            docCreateApp.saveContent();
        }
    };
}



/**
 * 初始化编辑器
 */
function createEditorInit(app){
    editorConfig.onCreated = function(IDomEditor){
        //防止wangeditor初始化警告
        if(INIT_STATUS == 0){
            INIT_STATUS = 1;
            app.selectTreeNode.type = 0;
        }
    }
    const editor = createEditor({
        selector: '#editor-container',
        config: editorConfig,
        mode: 'default'
    });
    app.editor.editor = editor;
    const toolbar = createToolbar({
        editor,
        selector: '#toolbar-container',
        config: toolbarConfig,
        mode: 'default', // or 'simple'
    });
}

/**
 * 获取章节列表
 */
function getChapterList(app){
    const param = {
        infoId: app.getDocData.mainId
    }
    const url = "/doc/info/chapter/list";
    tool.formJsonRequest(url, param, null, function (data) {
        if (data.code === "0000") {
            app.shareCode = data.data.shareCode;
            app.chapterList = [
                {
                    mainId: 0,
                    title: '目录',
                    parentId: 0,
                    children: data.data.chapterList,
                    type: 0, //0目录；1章节
                    treeIndex: '0'
                }
            ];
        } else {
            ElMessage({
                showClose: true,
                message: data.message,
                type: 'error'
            });
        }
    });
}

/**
 * 删除章节信息
 */
function deleteChapter(app, param){
    const url = "/doc/info/chapter/delete";
    tool.formJsonRequest(url, param, null, function (data) {
        if (data.code === "0000") {
            getChapterList(app);
            app.selectTreeNode = {};
            if(app.editor && app.editor.editor){
                app.editor.editor.disable();
            }
            app.curContent = null;
        } else {
            ElMessage({
                showClose: true,
                message: data.message,
                type: 'error'
            });
        }
    });
}

/**
 * 保存章节信息
 */
function saveChapter(app){
    const param = app.chapterForm;
    const url = "/doc/info/chapter/save";
    tool.formJsonRequest(url, param, null, function (data) {
        if (data.code === "0000") {
            getChapterList(app);
            app.chapterOption.isShow = false;
        } else {
            ElMessage({
                showClose: true,
                message: data.message,
                type: 'error'
            });
        }
    });
}

/**
 * 保存章节信息
 */
 function updateChapter(app){
    const param = app.chapterForm;
    const url = "/doc/info/chapter/update";
    tool.formJsonRequest(url, param, null, function (data) {
        if (data.code === "0000") {
            getChapterList(app);
            app.chapterOption.isShow = false;
        } else {
            ElMessage({
                showClose: true,
                message: data.message,
                type: 'error'
            });
        }
    });
}

/**
 * 获取文档内容
 */
 function getContent(app){
    createEditorInit(app);
    const param = {
        chapterId: app.selectTreeNode.mainId
    }
    const url = "/doc/info/docment/conent";
    tool.formJsonRequest(url, param, null, function (data) {
        if (data.code === "0000") {
            if(data.data == null){
                //未保存文档内容
                app.editor.editor.setHtml("");
            }else{
                app.curContent = data.data;
                app.editor.editor.setHtml(data.data.content);
            }
        } else {
            ElMessage({
                showClose: true,
                message: data.message,
                type: 'error'
            });
        }
    });
}

/**
 * 保存文档内容
 */
 function saveContent(app, content, contentText){
    const param = {
        chapterId: app.selectTreeNode.mainId,
        content: content,
        contentText: contentText
    }
    const url = "/doc/info/content/save";
    tool.formJsonRequest(url, param, null, function (data) {
        if (data.code === "0000") {
            ElMessage({
                showClose: true,
                message: '保存成功',
                type: 'success'
            });
        } else {
            ElMessage({
                showClose: true,
                message: data.message,
                type: 'error'
            });
        }
    });
}

/**
 * 关闭dialog的提示信息
 * @param app
 */
 function dialogCloseTips(app) {
    var confirmMessage = "";
    if (app.chapterOption.type == 0) {
        confirmMessage = "是否放弃新增章节信息？";
    } else {
        confirmMessage = "是否放弃修改章节信息？";
    }
    var obj = app;
    app.$confirm(confirmMessage).then(function () {
        obj.chapterOption.isShow = false;
    }).catch(function () { });
}
</script>
<style>
    :root {
        --doc-border: 1px solid #BEBEBE;
    }
    .doc_create_container {
        position: relative;
        width: 100%;
        height: 100%;
        border-top: var(--doc-border);
    }
    .doc_create_container .doc_create_letf {
        border-right: var(--doc-border);
        padding-top: 5px;
        padding-bottom: 5px;
    }
    .custom_node_item {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 16px;
        padding-right: 8px;
    }
    .custom_node_item .node_item_title {
        height: 100%;
        max-width: 160px;
        display: flex;
        justify-content: left;
        overflow: hidden;
    }
    .custom_node_item .node_item_group {
        width: 125px;
        display: flex;
        overflow: hidden;
    }
    .custom_node_item .node_item_operate {
        width: 36px;
        height: 100%;
        text-align: center;
    }
    .doc_create_dialog .el-main{
        padding: 0px;
    }
    .bt_save_span {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: calc(100% - 20px);
        height: 40px;
        border-bottom: var(--doc-border);
        padding: 5px 8px 5px 8px;
    }
    #editor—wrapper {
        width: 100%;
        height: calc(100% - 60px);
        z-index: 100; /* 按需定义 */
    }
    #editor-container { height: 500px; }
</style>